<!-- 基建费用 -->
<template>
  <div>
    <Row>
      <Col>
        <DatePicker
          type="daterange"
          v-model="date"
          placeholder="请选择周期"
          @on-change="changetype"
          clearable
          style="width: 200px"
        ></DatePicker>
      </Col>
      <Col class="ivu-ml-16">
        <Select
          v-model="params.construct_id"
          v-width="200"
          placeholder="请选择费用项目"
          filterable
          @on-change="changetype"
          clearable
        >
          <Option v-for="it in typeList" :value="it.id" :key="it.name">{{
            it.name
          }}</Option>
        </Select>
      </Col>
      <Col class="ivu-ml-16">
        <Button
          type="primary"
          @click="changeAdd('add', { id: '' })"
          v-hasC="{
            name: '-v1-marketing-construct-update-consume-record',
            flag: '/v1/marketing/construct/update-consume-record',
          }"
          >费用录入</Button
        >
      </Col>
    </Row>
    <div class="ivu-mt-16">
      <Table :columns="columns" :data="data" :max-height="550">
        <template slot-scope="{ row }" slot="status">
          <Badge
            v-if="row.consume_status == '1'"
            status="error"
            text="未开始"
          ></Badge>
          <Badge
            v-if="row.consume_status == '2'"
            status="warning"
            text="进行中"
          ></Badge>
          <Badge
            v-if="row.consume_status == '3'"
            status="success"
            text="已完成"
          ></Badge>
          <Badge
            v-if="row.consume_status == '-1'"
            status="error"
            text="已删除"
          ></Badge>
        </template>
        <template slot-scope="{ row }" slot="option">
          <a
            type="primary"
            @click="changeAdd('edit', row)"
            v-hasC="{
              name: '-v1-marketing-construct-update-consume-record2',
              flag: '/v1/marketing/construct/update-consume-record',
            }"
            v-if="row.consume_status !== -1"
            :disabled="(row.consume_status == '3' || row.is_disabled) && false"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-if="row.consume_status !== -1"
            v-hasCC="[
              {
                name: '-v1-marketing-construct-update-consume-record2',
                flag: '/v1/marketing/construct/update-consume-record',
              },
              {
                name: '-v1-marketing-construct-delete-consume-record',
                flag: '/v1/marketing/construct/delete-consume-record',
              },
            ]"
          ></Divider>
          <a
            type="primary"
            @click="deleteTag(row)"
            v-hasC="{
              name: '-v1-marketing-construct-delete-consume-record',
              flag: '/v1/marketing/construct/delete-consume-record',
            }"
            v-if="row.consume_status !== -1"
            :disabled="row.is_disabled"
            >删除</a
          >
        </template>
      </Table>
      <div
        class="ivu-mt iuv-text-center"
        style="display:flex;justify-content: center;"
      >
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="formSize"
          @on-page-size-change="formChangePage"
        ></Page>
      </div>
    </div>
    <Modal
      v-model="modalStatus"
      :title="modalTitle"
      width="650"
      @on-cancel="handleCancel('formD')"
    >
      <Form
        ref="formD"
        :model="formData"
        :rules="ruleValidate"
        :label-width="80"
      >
        <FormItem label="模式" prop="consume_type">
          <RadioGroup v-model="formData.consume_type">
            <Radio :label="1">一次记入</Radio>
            <Radio :label="2">周期记入</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="费用项目" prop="construct_id">
          <Select
            v-width="200"
            v-model="formData.construct_id"
            placeholder="请选择费用项目"
            filterable
            clearable
            @on-change="changeconst"
          >
            <Option v-for="it in typeList" :value="it.id" :key="it.name">{{
              it.name
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="渠道" prop="source_channel_id">
          <Select
            v-model="formData.source_channel_id"
            v-width="200"
            placeholder="请选择渠道类型"
            filterable
            clearable
          >
            <OptionGroup
              :label="item.source_name"
              v-for="item in sourcechannelList"
              :key="item.id"
            >
              <Option v-for="it in item.children" :value="it.id" :key="it.id">{{
                it.source_name
              }}</Option>
            </OptionGroup>
          </Select>
        </FormItem>
        <FormItem
          label="费用"
          prop="consume"
          :rules="{
            required: true,
            validator: validateconsume,
            trigger: 'blur',
            type: 'number',
          }"
        >
          <InputNumber
            :min="1"
            :max="999999"
            v-model="formData.consume"
            placeholder="请输入费用"
            style="width:200px"
          ></InputNumber>
        </FormItem>
        <FormItem
          label="日期"
          prop="time"
          v-if="+formData.consume_type === 1"
          :rules="{
            required: +formData.consume_type === 1 ? true : false,
            message: '请选择开始时间',
            trigger: 'change',
            type: 'date',
          }"
        >
          <DatePicker
            v-model="formData.time"
            type="date"
            placeholder="请选择日期"
            style="width: 200px"
          ></DatePicker>
        </FormItem>
        <FormItem label="周期" v-else>
          <Row :gutter="24">
            <Col span="10">
              <FormItem
                prop="start_time"
                :rules="{
                  required: +formData.consume_type === 2 ? true : false,
                  message: '请选择开始时间',
                  trigger: 'change',
                  type: 'date',
                }"
              >
                <DatePicker
                  type="date"
                  v-model="formData.start_time"
                  placeholder="请输入开始日期"
                  style="width: 200px"
                ></DatePicker>
              </FormItem>
            </Col>
            <Col span="14">
              <FormItem prop="end_time">
                <DatePicker
                  type="date"
                  v-model="formData.end_time"
                  placeholder="请输入结束日期"
                  style="width: 200px"
                ></DatePicker>
              </FormItem>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleCancel('formD')">取消</Button>
        <Button
          type="primary"
          @click="handleSubmit('formD')"
          :loading="modalLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from "dayjs";
import {
  conditionList,
  constructConsume,
  updateconsumeRecord,
  deleteconsumeRecord,
  selectChannel,
} from "@/api/hqapi/networkMarketing.js";
export default {
  data() {
    return {
      formD: "formD",
      columns: [
        { title: "费用", key: "consume", minWidth: 120, fixed: "left" },
        {
          title: "渠道",
          key: "source_channel_name",
          minWidth: 120,
          render: (h, params) => {
            return h(
              "span",
              `${params.row.source_channel_name}/${params.row.construct_name}`
            );
          },
        },
        { title: "周期", key: "cycle_time", minWidth: 260 },
        { title: "状态", slot: "status", minWidth: 120 },
        { title: "模式", key: "consume_type_name", minWidth: 120 },
        { title: "录入人", key: "member_name", minWidth: 120 },
        { title: "录入日期", key: "created_at", minWidth: 120 },
        { title: "操作", slot: "option", width: "140", fixed: "right" },
      ],
      data: [],
      date: [],
      channelList: [],
      total: 0,
      params: { construct_id: "", page: 1, pageSize: 10 },
      pageOpts: [10, 20, 50, 100],
      modalStatus: false,
      modalTitle: "",
      formData: {
        id: "",
        time: "",
        start_time: "",
        end_time: "",
        construct_id: "",
        consume: null,
        consume_type: 1,
        source_channel_id: "",
      },
      sourcechannelList: [],
      ruleValidate: {
        consume_type: [
          {
            required: true,
            message: "请选择模式",
            trigger: "change",
            type: "number",
          },
        ],
        construct_id: [
          { required: true, message: "请选择费用项目", trigger: "change" },
        ],
        source_channel_id: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        end_time: [
          { required: true, validator: this.validateDate, trigger: "change" },
        ],
      },
      typeList: [],
      modalLoading: false,
      //获取上个月到之后的时间
      options: {
        disabledDate(date) {
          let temMonth = dayjs(new Date())
            .subtract(1, "month")
            .format("YYYY-MM");
          let temMonthStr = temMonth + "-01";
          let preMonth = dayjs(temMonthStr)
            .subtract(1, "day")
            .format("YYYY-MM-DD");
          let time = new Date(preMonth).getTime();
          return date && date.valueOf() < time;
        },
      },
      options1: {
        disabledDate(date) {
          let temMonth = dayjs(new Date())
            .subtract(1, "month")
            .format("YYYY-MM");
          let temMonthStr = temMonth + "-01";
          let preMonth = dayjs(temMonthStr)
            .subtract(1, "day")
            .format("YYYY-MM-DD");
          let time = new Date(preMonth).getTime();
          return date && date.valueOf() < time;
        },
      },
      options2: {
        disabledDate(date) {
          let temMonth = dayjs(new Date())
            .subtract(1, "month")
            .format("YYYY-MM");
          let temMonthStr = temMonth + "-01";
          let preMonth = dayjs(temMonthStr)
            .subtract(1, "day")
            .format("YYYY-MM-DD");
          let time = new Date(preMonth).getTime();
          return date && date.valueOf() < time;
        },
      },
    };
  },
  mounted() {},
  methods: {
    // validatestartDate(rule, value, callback){
    //       if (value === '') {
    //           callback(new Error('请选择开始时间'));
    //       } else {
    //         console.log(this.$Date(this.formData.start_time).format('YY-MM-DD'),'1')
    //           if (this.$Date(this.formData.start_time).format('YY-MM-DD')<this.$Date(this.formData.end_time).format('YY-MM-DD')) {
    //                callback(new Error('开始时间要小于等于开始时间'));
    //           }
    //           callback();
    //       }
    //   },
    validateconsume(rule, value, callback) {
      if (value === "") {
        callback(new Error("请填写费用"));
      } else {
        // console.log(value ,'qqq')
        if (!Number.isInteger(value)) {
          callback(new Error("请输入整数"));
        }
        callback();
      }
    },
    validateDate(rule, value, callback) {
      if (value === "") {
        callback(new Error("请选择结束时间"));
      } else {
        // console.log(this.$Date(this.formData.start_time).format('YY-MM-DD'),'1')
        if (
          this.$Date(this.formData.start_time).format("YY-MM-DD") >
          this.$Date(this.formData.end_time).format("YY-MM-DD")
        ) {
          callback(new Error("结束时间不能早于开始时间"));
        }
        callback();
      }
    },
    initial(e) {
      if (e == "name2") {
        this.getconditionList();
        this.getconstructConsume();
      }
    },
    // 获取费用类型
    getconditionList() {
      conditionList().then((res) => {
        this.typeList = res;
      });
    },
    changeconst(val) {
      this.formData.source_channel_id = "";
      if (val) {
        this._getselectChannel(val);
      }
    },
    // 获取渠道数据
    _getselectChannel(val) {
      selectChannel({ construct_id: val }).then((res) => {
        this.sourcechannelList = res;
      });
    },
    // 获取数据
    getconstructConsume() {
      const params = {
        start_time: this.date[0]
          ? this.$Date(this.date[0]).format("YY-MM-DD")
          : "",
        end_time: this.date[1]
          ? this.$Date(this.date[1]).format("YY-MM-DD")
          : "",
        construct_id: this.params.construct_id,
        page: this.params.page,
        pageSize: this.params.pageSize,
      };
      constructConsume(params).then((res) => {
        this.data = res.list;
        this.total = res.total;
      });
    },
    changetype() {
      this.getconstructConsume();
    },
    formSize(index) {
      this.params.page = index;
      this.getconstructConsume();
    },
    formChangePage(e) {
      this.params.pageSize = e;
      this.getconstructConsume();
    },
    changeAdd(e, row) {
      // console.log(row,'e')
      this.formData.id = row.id;

      if (e == "add") {
        this.modalTitle = "录入费用";
      } else {
        this.modalTitle = "编辑费用";
        this.formData = {
          id: row.id,
          time: row.start_date,
          start_time: row.start_date,
          end_time: row.end_date,
          construct_id: row.construct_id,
          source_channel_id: row.source_channel_id,
          consume: row.consume * 1,
          consume_type: row.consume_type * 1,
        };
        this._getselectChannel(row.construct_id);
      }
      this.modalStatus = true;
    },
    handleCancel(name) {
      // this.formData.consume_type = 1,
      this.modalStatus = false;
      this.$refs[name].resetFields();
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          const params = {
            id: this.formData.id,
            start_time:
              this.formData.consume_type === 1
                ? this.$Date(this.formData.time).format("YYYY-MM-DD")
                : this.formData.start_time
                ? this.$Date(this.formData.start_time).format("YYYY-MM-DD")
                : "",
            end_time:
              this.formData.consume_type === 2
                ? this.formData.end_time
                  ? this.$Date(this.formData.end_time).format("YYYY-MM-DD")
                  : ""
                : "",
            construct_id: this.formData.construct_id,
            source_channel_id: this.formData.source_channel_id,
            consume: this.formData.consume * 1,
            consume_type: this.formData.consume_type,
          };
          this.modalLoading = true;
          updateconsumeRecord(params)
            .then((res) => {
              if (this.modalTitle == "录入费用") {
                this.$Message.success("新增成功");
                this.modalLoading = false;
                this.handleCancel(name);
                this.getconstructConsume();
              } else {
                this.$Message.success("编辑成功");
                this.modalLoading = false;
                this.handleCancel(name);
                this.getconstructConsume();
              }
            })
            .catch(() => {
              this.modalLoading = false;
            });
        }
      });
    },
    /* 删除 */
    deleteTag(row) {
      this.$Modal.confirm({
        title: "删除确认",
        content: `是否确认删除${row.consume}元${row.source_channel_name}/${row.construct_name}`,
        loading: true,
        onOk: () => {
          deleteconsumeRecord({ id: row.id }).then((res) => {
            this.$Modal.remove();
            this.$Message.success("删除成功");
            this.getconstructConsume();
          });
        },
      });
    },
  },
};
</script>
